package com.hallowd.purcom;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class SignUpActivity extends Activity {
    private static final String TAG = SignUpActivity.class.getSimpleName();

    Button mSignUpButton;
    EditText mEmail;
    EditText mPassword;
    EditText mName;
    EditText mSurname;
    EditText mLocation;
    TextView mLoginLink;
    Spinner mSpinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);

        mEmail = (EditText) findViewById(R.id.email);
        mPassword = (EditText) findViewById(R.id.password);
        mName = (EditText) findViewById(R.id.name);
        mSurname = (EditText) findViewById(R.id.surname);
        mLocation = (EditText) findViewById(R.id.location);


        mSpinner = (Spinner) findViewById(R.id.spinner);
        (new SkillsAsyncTask()).execute();



        mSignUpButton = (Button) findViewById(R.id.signupButton);
        mSignUpButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                (new SignUpAsyncTask()).execute();
            }
        });

        mLoginLink = (TextView) findViewById(R.id.loginLink);
        mLoginLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });
    }


    private class SkillsAsyncTask extends AsyncTask<String, Integer, List<String>> {
        @Override
        protected List<String> doInBackground(String... params) {
            String url = "http://titan.cmpe.boun.edu.tr:8089/purcom/mobile/skill/list";

            HttpClient httpclient = new DefaultHttpClient();
            HttpUriRequest request = new HttpGet(url);

            try {
                HttpResponse response = httpclient.execute(request);
                if (response.getStatusLine().getStatusCode() == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

                    StringBuilder builder = new StringBuilder();
                    for (String line = null; (line = reader.readLine()) != null; ) {
                        builder.append(line).append("\n");
                    }

                    JSONTokener tokener = new JSONTokener(builder.toString());
                    JSONArray finalResult = new JSONArray(tokener);

                    List<String> skills = new ArrayList<String>();
                    for (int i=0; i < finalResult.length(); i++) {
                        skills.add(finalResult.getJSONObject(i).getString("name"));
                    }

                    return skills;
                }
                else
                    Log.d(TAG, "Signup Failed");
            } catch (IOException e) {
                Log.d(TAG, "Connection problem occured");
            } catch (JSONException e) {
                Log.d(TAG, "JSON Parse error");
            }

            return null;
        }

        protected void onPostExecute(List<String> skills) {

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(SignUpActivity.this, android.R.layout.simple_spinner_item, skills);
            if(skills != null) {
                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                mSpinner.setAdapter(adapter);
            }
        }
    }


    private class SignUpAsyncTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            String url = "http://titan.cmpe.boun.edu.tr:8089/purcom/mobile/user/signup/";
            String email = mEmail.getText().toString();
            String password = mPassword.getText().toString();
            String name = mName.getText().toString();
            String surname = mSurname.getText().toString();
            String location = mLocation.getText().toString();
         //   String selectedSkill = mSpinner.getSelectedItem().toString();
           // url = url + "?email="+email+"&password="+password+"&name="+name+"&surname="+surname+"&location="+location;
            Log.d(TAG, url);

            HttpClient httpclient = new DefaultHttpClient();
           // HttpUriRequest request = new HttpPost(url);
            HttpPost request=new HttpPost(url);
            request.addHeader("Content-Type","application/json");
            request.addHeader("Accept","application/json");
            // 3. build jsonObject
            try{
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("email", email);
            jsonObject.accumulate("password", password);
            jsonObject.accumulate("name", name);
            jsonObject.accumulate("surname", surname);
            jsonObject.accumulate("location", location);
          //  jsonObject.accumulate("", selectedSkill);
            // 4. convert JSONObject to JSON to String


            String  json = jsonObject.toString();

            // ** Alternative way to convert Person object to JSON string usin Jackson Lib
            // ObjectMapper mapper = new ObjectMapper();
            // json = mapper.writeValueAsString(person);

                // 5. set json to StringEntity
                StringEntity se = new StringEntity(json);

                // 6. set httpPost Entity
                request.setEntity(se);

                HttpResponse response = httpclient.execute(request);
                if (response.getStatusLine().getStatusCode() == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

                    StringBuilder builder = new StringBuilder();
                    for (String line = null; (line = reader.readLine()) != null; ) {
                        builder.append(line).append("\n");
                    }

                    Log.d(TAG, "Signup " + builder.toString());
                    return builder.toString();
                }
                else
                    Log.d(TAG, "Signup Failed");
            } catch (Exception e) {
                Log.d(TAG, e.toString());
                Log.d(TAG, e.getCause().toString());
                Log.d(TAG, "Connection problem occured");
            }

            return null;
        }

        protected void onPostExecute(String result) {
            AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
            builder.setMessage("You successfully signed up!")
                    .setTitle("SignUp Result")
                    .setPositiveButton(android.R.string.ok, null);
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    }

}
